package com.cszy.yydqbfq.dialog

import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.PopupWindow
import android.widget.Toast
import androidx.core.net.toUri
import com.bumptech.glide.Glide
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.databinding.PopBottomCreateSongBinding
import com.cszy.yydqbfq.ext.click
import com.cszy.yydqbfq.listener.OnCreateSongListener
import com.cszy.yydqbfq.utils.SpUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hnyyac.ad.mds.utils.BaseAdConstants


class BottomCreateSongPop(
    private val mContext: Context, onCreateSongListener: OnCreateSongListener,
    oldSongName: String = "", oldCoverUri: String = "", val songlistbeanId :Long,
) {
    private var onCreateSongListener: OnCreateSongListener? = onCreateSongListener
    private lateinit var binding: PopBottomCreateSongBinding
    private var newGromoreFeedAd: NewGroMoreFeedAdManager? = null

    private var pernissonTopdialog: PermissoTipDialog? = null

    // 保存 oldSongName 为成员变量
    private var oldSongName: String = oldSongName
    private var oldCoverUri: String = oldCoverUri

    private var coverUri: String? = null
    private fun initBinding() {
        binding = PopBottomCreateSongBinding.inflate(LayoutInflater.from(mContext))
    }


    private val popupWindow = PopupWindow().apply {
        initBinding()
        contentView = binding.root
        width = ViewGroup.LayoutParams.MATCH_PARENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isOutsideTouchable = true
        isFocusable = true
        // 更改输入法模式为调整大小
        softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        animationStyle = R.style.PopupAnimation
    }

    fun show(anchorView: View, position: Int) {
        //信息流
        initLister(position)
        initViewStatus()
        popupWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0)
    }

    private fun initViewStatus() {
        try {
            binding.etGedanTitle.setText(oldSongName)
            if (oldCoverUri != "") {
                setCoverUri(oldCoverUri.toUri())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initLister(position: Int) {
        var frame_gedan = binding.frameGedan
        newGromoreFeedAd = NewGroMoreFeedAdManager(
            mContext as Activity,
            BaseAdConstants.FEEDAD_Id,
            frame_gedan,
            position
        )
        newGromoreFeedAd?.loadAd()


        binding.tvCancel.click {
            dismiss()
        }

        binding.tvConrim.click {
            if (binding.etGedanTitle.text.toString().isEmpty()) {
                Toast.makeText(mContext, "请输入歌单名称", Toast.LENGTH_SHORT).show()
                return@click
            }
            onCreateSongListener?.onEditSuccess(
                binding.etGedanTitle.text.toString(),
                coverUri ?: ""
                ,songlistbeanId
            )
            dismiss()
        }

        binding.ivCover.click {
            if (XXPermissions.isGranted(
                    mContext,
                    android.Manifest.permission.READ_MEDIA_IMAGES
                )
            ) {
                selectImage()

            } else {
                request_Permission(
                    mContext,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    "相册权限",
                    "需要获取您的手机相册权限"
                )
            }
        }

        binding.ivXiala.click {
            dismiss()
        }

        binding.tvDelete.click {
            onCreateSongListener?.onDeleteGedan(songlistbeanId)
            dismiss()
        }
    }


    open fun setCoverUri(uri: Uri) {
        coverUri = uri.toString()
        if (coverUri != null) {
            Glide.with(mContext)
                .load(coverUri!!)
                .into(binding.ivCover)
        }
    }

    // 调用图片选择器
    fun selectImage() {
        onCreateSongListener?.onImageSelected()
    }

    private fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        // 检查是否已标记为"不再询问"
        if (!SpUtils.getInstance().getBoolean(permisson_name)) { // 没有获取该权限或者没有永久拒绝
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            // 申请单个权限
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (pernissonTopdialog != null) {
                        pernissonTopdialog!!.dismiss()
                    }
                    if (!allGranted) {

                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    Toast.makeText(context, "获取 $permisson_name 权限成功", Toast.LENGTH_SHORT)
                        .show()
                    selectImage()
                }

                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        showDoNotAskAgainDialog(
                            context,
                            req_permisson,
                            permisson_name
                        )
                    } else {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }

                    }
                }
            })
    }

    /**
     * 用户单次拒绝
     */
    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }

    /**
     * 用户多次拒绝
     */
    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = UserRefusedPermissonDialog(context, permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }

    fun dismiss() {
        //隐藏软键盘
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(popupWindow.contentView.windowToken, 0)
        }
        popupWindow.dismiss()
    }
}